package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;


import com.tanhua.dubbo.MongoApplication;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementsApiImpl implements MovementsApi {

    //注入对应的mongo
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired//注入异步对象
    private TimeLineService timeLineService;

    @Override//发布动态,将动态保存到数据库
    public String save(Movement movement) {
        //1.将动态保存到数据库当中
        mongoTemplate.insert(movement);
        //2.因为以下内容采用线程来解决,所以抽取工具类采用spring的异步来处理
        timeLineService.saveTimeLine(movement);
        //3.将动态id返回
        return movement.getId().toString();
    }

    @Override//查询个人动态
    public List<Movement> findByUserId(Integer page, Integer pagesize, Long userId) {
        //1.构建Criteria
        Criteria criteria = Criteria.where("userId").is(userId).and("state").is(1);
        //2.构建Query
        Query query = Query.query(criteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        //3.根据条件查询
        return mongoTemplate.find(query, Movement.class);
    }

    @Override//查询好友动态
    public List<Movement> findByFriendId(Long friendId, Integer page, Integer pagesize) {
        //构建Criteria
        Criteria lineCriteria = Criteria.where("friendId").is(friendId);
        Query lineQuery = Query.query(lineCriteria)
                .with(Sort.by(Sort.Order.desc("created")))
                .limit(pagesize)
                .skip((page - 1) * pagesize);
        //2.调用查询中间表,获取到所有可查看的动态信息
        List<MovementTimeLine> lines = mongoTemplate.find(lineQuery, MovementTimeLine.class);
        //3.将集合中的所有movementId提取出来
        List<ObjectId> ids = CollUtil.getFieldValues(lines, "movementId", ObjectId.class);
        //4.构建Criteria,根据ids在动态表中查找到对应的动态
        Criteria criteria = Criteria.where("id").in(ids).and("state").is(1);
        Query query = Query.query(criteria);
        return mongoTemplate.find(query, Movement.class);
    }

    @Override//根基redis中的ids来查询对应的动态
    public List<Movement> findByIds(String[] movementIds, Integer page, Integer pagesize) {
        //1.构建查询条件
        Criteria criteria = Criteria.where("id").in(movementIds).and("state").is(1);
        Query query = Query.query(criteria)
                .limit(pagesize)
                .skip((page - 1) * pagesize);
        List<Movement> list = mongoTemplate.find(query, Movement.class);
        return list;
    }

    @Override//随机查询指定条数的动态
    public List<Movement> RandomMovement(Integer count) {
        //本质上用到的是mongoDb的采样
        //设置采样配置
        TypedAggregation<Movement> aggregation = TypedAggregation.newAggregation(Movement.class, Aggregation.sample(count));
        //查询
        AggregationResults<Movement> aggregate = mongoTemplate.aggregate(aggregation, Movement.class);
        //从采样结果中,获取到真实的数据
        return  aggregate.getMappedResults();
    }

    @Override//根据动态id查询单条动态
    public Movement findById(String id) {
        //根据id查询动态，Movement返回给api层
        return  mongoTemplate.findById(id, Movement.class);
    }

    @Override//审核后修改动态的状态码
    public void updateState(String movementId, Integer state) {
        //1.构建条件
        Query query = Query.query(Criteria.where("id").is(new ObjectId(movementId)));
       //2.构建update
        Update update = new Update();
        update.set("state",state);
        mongoTemplate.updateMulti(query,update,Movement.class);
    }

    @Override//后台分页查询动态信息
    public PageResult findByPage(Integer page, Integer pagesize, Long uid, Integer status) {
        //1.构建条件
        Criteria criteria = Criteria.where("userId").is(uid);
        //2.构建query
        Query query = Query.query(criteria);
        //3.查询总数
        long count = mongoTemplate.count(query, Movement.class);
        //4.构建分页条件
        query = query.with(Sort.by(Sort.Order.desc("created")))
                .skip((page - 1) * pagesize)
                .limit(pagesize);
        //5.重新查询
        List<Movement> vo = mongoTemplate.find(query, Movement.class);
        //6.构建PageResult
        return new PageResult(page,pagesize,count,vo);
    }
}
